package com.jason.coroutines.test

import com.jason.coroutines.doSomethingUsefulOne
import com.jason.coroutines.doSomethingUsefulTwo
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis

/**
 * Description :
 * Created by vic
 * Created Time 2023/9/3
 */
/*
fun main() = runBlocking {
//sampleStart
    *//* val result = withTimeoutOrNull(1300L) {
         repeat(2) { i ->
             println("I'm sleeping $i ...")
             delay(500L)
         }
         "OK" // 在它运行得到结果之前取消它
     }

     println(result ?:"Done")
     println("Result is $result")*//*
//sampleEnd

//    runBlocking {
//        launch {
//            println("runBlocking 1")
//        }
//        println("delay 1" )
//        delay(1000)
//    }

    runBlocking {
        repeat(10) {
            launch {
                var resource: Resource? = null
                try {
                    resource = withTimeout(60) {
                        delay(50)
                        Resource()
                    }
//                    println("runBlocking  close ")
//                    resource?.close()
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    resource?.close()
                    println("finally  close  it= $it ")
                }
            }
        }

    }

    runBlocking {
        launch {
            println("runBlocking 2")
        }
        println("delay 2")
        delay(3000)
    }

    println("main   end ")
}*/

fun main() = runBlocking {
    /*val time = measureTimeMillis {
        val one = doSomethingUsefulOne()
        val two = doSomethingUsefulTwo()
        println("The answer is ${one + two}")
    }
    println("Completed in $time ms")*/


    val time1 = measureTimeMillis {
        val one = launch { doSomethingUsefulOne() }
        val two = launch { doSomethingUsefulTwo() }

        println("The answer is ${one.isCompleted}  + ${two.isCompleted}")
    }
    val time = measureTimeMillis {
        val one = async { doSomethingUsefulOne() }
        val two = async { doSomethingUsefulTwo() }
        println("The answer is ${one.await() + two.await()}")
    }
    //这⾥快了两倍，因为两个协程并发执⾏。请注意，使⽤协程进⾏并发总是显式的。
    println("Completed in $time ms")
}
